package com.todo.interceptor;

import com.todo.constant.JwtClaimsConstant;
import com.todo.dto.UserDTO;
import com.todo.properties.JwtProperties;
import com.todo.utils.JwtUtil;
import com.todo.utils.UserHolder;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private JwtProperties jwtProperties;


    /**
     * 校验jwt
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*String token = request.getHeader("authorization");
        if (StrUtil.isBlankIfStr(token)){
            response.setStatus(401);
            return false;
        }
        //基于token 获取redis中用户
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(RedisConstants.LOGIN_USER_KEY + token);
        if (userMap.isEmpty()){
            //不存在，拦截
            response.setStatus(401);
            return false;
        }
        //Map转对象
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
        //存在，保存用户信息到ThreadLocal
        UserHolder.saveUser(userDTO);
        //刷新token有效期
        stringRedisTemplate.expire(RedisConstants.LOGIN_USER_KEY+token,RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        //放行*/
        //判断是否需要拦截 （ThreadLocal中是否有用户）
        /*log.info(String.valueOf(Thread.currentThread().getId()));
        System.out.println("当前线程id"+Thread.currentThread().getId());
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }*/

        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getUserTokenName());

        //2、校验令牌
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            ///存入userDTO放入LocalThread
            String uid = claims.get(JwtClaimsConstant.USER_UID).toString();//获取用户uid
            log.info("token解析后获取的uid："+uid);
            //将用户uid用ThreadLocal进行存储
            UserDTO userDTO =  new UserDTO();
            userDTO.setUid(uid);
            UserHolder.saveUser(userDTO);
            log.info("当前用户id,{}", uid);
            //3、通过，放行
            return true;
        } catch (Exception ex) {
            //4、不通过，响应401状态码
            response.setStatus(401);
            return false;
        }
    }

}
